import { ESForest } from "../esobjs/ESForest";
import { MyProjectManager } from "../MyProjectManager";
import { Destroyable, react, reactJson, Event, track, bind, HasOwner, createNextAnimateFrameEvent } from "xbsj-xe2/dist-node/xe2-base-utils";
import { ObjResettingWithEvent, SceneObject, Viewer } from 'xbsj-xe2/dist-node/xe2-base-objects';
import { getRandomElement, getUrlParam } from "../utils";
import { AddTree } from "./addTree";
import axios from "axios";
import { ElMessage } from "element-plus";
import { reqFeEditorMultioperation } from "@/api";
import { EditTree } from "./editTree";

class ESForestResettting extends Destroyable {
    constructor(esForestManager: ESForestManager, owner: MyProjectManager) {
        super();

    }
}

export class ESForestManager extends HasOwner<MyProjectManager> {

    // 服务路径
    private _esForestUrl = this.dv(react<string>(""));
    get esForestUrl() { return this._esForestUrl.value; }
    get esForestUrlChanged() { return this._esForestUrl.changed; }
    set esForestUrl(value: string) { this._esForestUrl.value = value; }


    // 是不是ESForest服务
    private _isESForestService = this.dv(react<boolean>(false));
    get isESForestService() { return this._isESForestService.value; }
    get isESForestServiceChanged() { return this._isESForestService.changed; }
    set isESForestService(value: boolean) { this._isESForestService.value = value; }

    //服务ip
    get esForestIp() {
        return this.esForestUrl.match(/^(https?:\/\/[^\/]+)/)?.[1]
    }

    // 样地id
    private _esForestPlotId = this.dv(react<string>(""));
    get esForestPlotId() { return this._esForestPlotId.value; }
    get esForestPlotIdChanged() { return this._esForestPlotId.changed; }
    set esForestPlotId(value: string) { this._esForestPlotId.value = value; }


    // 样地名称
    private _esForestPlotName = this.dv(react<string>(""));
    get esForestPlotName() { return this._esForestPlotName.value; }
    get esForestPlotNameChanged() { return this._esForestPlotName.changed; }
    set esForestPlotName(value: string) { this._esForestPlotName.value = value; }

    // 时间
    private _esForestTime = this.dv(react<string>(""));
    get esForestTime() { return this._esForestTime.value; }
    get esForestTimeChanged() { return this._esForestTime.changed; }
    set esForestTime(value: string) { this._esForestTime.value = value; }

    // 验证是不是ESForest服务
    async verifyESForestService() {
        try {
            // 添加请求头
            const token = localStorage.getItem("Authorization")
            const res = await axios({
                url: this.esForestUrl,
                method: 'get',
                headers: {
                    ...(token ? { 'Authorization': token } : {})
                },
            })

            if (res.data.data && res.data.data.hasOwnProperty("trees")) {
                this.isESForestService = true
                // eSForest url
                this.eSForest.url = this.esForestUrl
                const match = this.esForestUrl.match(/\/plot\/yangdi\/(.*)/)?.[1] as string
                const param = match.split("?").length == 1 ? match.split("/") : match.split("?")[0].split("/")
                // 样地id
                this.esForestPlotId = res.data.data.plot.id
                // 样地名称
                this.esForestPlotName = res.data.data.plot.name
                // 时间
                this.esForestTime = param[1]
                // 树种
                this.addTree.treeModelClasses = res.data.data.treeModelClasses
            } else {
                this.eSForest.url = ""
                this.isESForestService = false
                ElMessage.error('请输入正确的ESForest服务地址')
            }

        } catch (error) {
            this.eSForest.url = ""
            this.isESForestService = false
            ElMessage.error('请输入正确的ESForest服务地址')
            return false
        }

    }

    // ESForest
    private _eSForest = this.dv(this.owner.createSceneObject(ESForest) as ESForest);
    get eSForest() { return this._eSForest; }

    // 添加树
    private _addTree = this.dv(new AddTree(this.owner));
    get addTree() { return this._addTree; }

    // 编辑树
    private _editTree = this.dv(new EditTree(this.owner));
    get editTree() { return this._editTree; }

    // 飞向随机树
    flyToRandomTree() {
        const item = getRandomElement(this.eSForest.trees)
        if (!item) return;
        this.eSForest.flyToTree(item.id)
    }

    refresh() {
        if (!this.esForestUrl) return;
        const time = +new Date();
        const url = `${this.esForestIp}/plot/yangdi/${this.esForestPlotName}/${this.esForestTime}?time=${time}`
        console.log("url", url);
        this.esForestUrl = url
    }



    // 提交正在编辑的对象
    async submitFeEditorMultioperation() {
        try {

            const json = this.owner.forestSceneTreeWrapper?.json.root.children
            const param = {
                "sceneTree": json
            }
            const res = await reqFeEditorMultioperation(param)
            // @ts-ignore
            if (res.status != 'ok') return;
            ElMessage({
                message: `提交成功`,
                type: 'success',
            })
            this.owner.forestSceneTreeWrapper?.destroyAllSceneObjectTreeItems()
            this.owner.forestPropSceneTree = undefined
            this.refresh()
        } catch (error) {
            console.error(error);
        }
    }

    // 清除cimrts窗口
    private _clearESForestWindowEvent = this.dv(new Event());
    get clearESForestWindowEvent() { return this._clearESForestWindowEvent; }

    clear() {
        this.isESForestService = false

        // 是否是ESForest服务
        this.isESForestService = false
        // 清除ESForest窗口
        this.clearESForestWindowEvent.emit()
        // 场景树上的对象删除
        this.owner.forestSceneTreeWrapper?.destroyAllSceneObjectTreeItems()
        this.owner.propSceneTree = undefined
    }

    constructor(owner: MyProjectManager) {
        super(owner);

        {
            const updata = async (url: string) => {
                // 清除参数
                this.clear()
                if (!url) {
                    this.eSForest.url = ""
                    return;
                }
                await this.verifyESForestService()
            }
            this.dispose(this.esForestUrlChanged.don(updata))
        }
        // {
        //     this.dv(new ObjResettingWithEvent(this.esForestUrlChanged, () => {
        //         // esForest服务地址为空
        //         if (!this.esForestUrl) return undefined;
        //         return new ESForestResettting(this, this.owner);
        //     }))
        // }
    }
}